package sql

import (
	"bytes"
	"encoding/json"
	"errors"

	"github.com/xwb1989/sqlparser"
)

// ConvertPretty will transform sql to elasticsearch dsl, and prettify the output json
func ConvertPretty(sql string) (dsl string, table string, conditions []*Condition, err error) {
	dsl, table, conditions, err = Convert(sql)
	if err != nil {
		return dsl, table, nil, err
	}
	var prettifiedDSLBytes bytes.Buffer
	err = json.Indent(&prettifiedDSLBytes, []byte(dsl), "", "  ")
	if err != nil {
		return "", table, nil, err
	}
	return string(prettifiedDSLBytes.Bytes()), table, nil, err
}

// Convert will transform sql to elasticsearch dsl string
func Convert(sql string) (dsl string, table string, conditions []*Condition, err error) {
	stmt, err := sqlparser.Parse(sql)
	if err != nil {
		return "", "", nil, err
	}
	//sql valid, start to handle
	switch stmt.(type) {
	case *sqlparser.Select:
		dsl, table, conditions, err = handleSelect(stmt.(*sqlparser.Select))
	case *sqlparser.Update:
		return "", "", nil, errors.New("update not supported")
	case *sqlparser.Insert:
		return "", "", nil, errors.New("update not supported")
	case *sqlparser.Delete:
		return "", "", nil, errors.New("update not supported")
	}
	if err != nil {
		return "", "", nil, err
	}
	return dsl, table, conditions, nil
}
